import { Router } from 'express'
import bcrypt from 'bcryptjs'
import { loadUsers, saveUsers } from '../utils/fileStore.js'
import { generateUserId } from '../utils/id.js'
import { authenticateToken } from '../middleware/auth.js'
import { generateAccessToken, getBearerToken, verifyToken } from '../utils/jwt.js'

const router = Router()

router.post('/register', async (req, res) => {
  try {
    const { username, password, email } = req.body || {}
    if (!username || !password)
      return res.status(400).json({ code: 400, data: null, msg: '用户名和密码为必填项' })
    if (typeof username !== 'string' || username.length < 2 || username.length > 20)
      return res.status(400).json({ code: 400, data: null, msg: '用户名长度需在2~20之间' })
    if (typeof password !== 'string' || password.length < 6 || password.length > 20)
      return res.status(400).json({ code: 400, data: null, msg: '密码长度需在6~20之间' })

    const store = loadUsers()
    const exists = store.users.find((u) => u.username.toLowerCase() === username.toLowerCase())
    if (exists) return res.status(409).json({ code: 409, data: null, msg: '用户名已存在' })

    const id = generateUserId()
    const passwordHash = await bcrypt.hash(password, 10)
    const user = {
      id,
      username,
      email: email || undefined,
      passwordHash,
      avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(username)}`,
      createdAt: new Date().toISOString(),
      lastLoginAt: null,
    }
    store.users.push(user)
    if (!saveUsers(store))
      return res.status(500).json({ code: 500, data: null, msg: '保存用户失败' })

    const { passwordHash: _ignore, ...publicUser } = user
    return res.json({ code: 200, data: publicUser, msg: '注册成功' })
  } catch (e) {
    console.error(e)
    return res.status(500).json({ code: 500, data: null, msg: '服务器错误' })
  }
})

router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body || {}
    if (!username || !password)
      return res.status(400).json({ code: 400, data: null, msg: '用户名和密码为必填项' })

    const store = loadUsers()
    const user = store.users.find((u) => u.username.toLowerCase() === username.toLowerCase())
    if (!user) return res.status(401).json({ code: 401, data: null, msg: '用户名或密码错误' })

    const ok = await bcrypt.compare(password, user.passwordHash)
    if (!ok) return res.status(401).json({ code: 401, data: null, msg: '用户名或密码错误' })

    user.lastLoginAt = new Date().toISOString()
    saveUsers(store)

    const token = generateAccessToken(user)
    const { passwordHash: _ignore, ...publicUser } = user
    return res.json({ code: 200, data: { token, user: publicUser }, msg: '登录成功' })
  } catch (e) {
    console.error(e)
    return res.status(500).json({ code: 500, data: null, msg: '服务器错误' })
  }
})

router.get('/me', authenticateToken, (req, res) => {
  const store = loadUsers()
  const user = store.users.find((u) => u.id === req.user.id)
  if (!user) return res.status(404).json({ code: 404, data: null, msg: '用户不存在' })
  const { passwordHash: _ignore, ...publicUser } = user
  return res.json({ code: 200, data: publicUser, msg: '获取成功' })
})

router.post('/refresh', (req, res) => {
  const token = getBearerToken(req)
  if (!token) return res.status(400).json({ code: 400, data: null, msg: '缺少令牌' })
  try {
    const payload = verifyToken(token)
    const store = loadUsers()
    const user = store.users.find((u) => u.id === payload.sub)
    if (!user) return res.status(404).json({ code: 404, data: null, msg: '用户不存在' })
    const newToken = generateAccessToken(user)
    return res.json({ code: 200, data: { token: newToken }, msg: '刷新成功' })
  } catch {
    return res.status(401).json({ code: 401, data: null, msg: '令牌无效或已过期' })
  }
})

router.post('/logout', (_req, res) => {
  return res.json({ code: 200, data: null, msg: '已登出' })
})

// 验证令牌是否有效/过期
router.post('/validate-token', (req, res) => {
  try {
    const tokenFromBody = req.body?.token
    const tokenFromHeader = getBearerToken(req)
    const token = tokenFromBody || tokenFromHeader
    if (!token) {
      // 与前端拦截器兼容：始终返回 code=200，data 为布尔值
      return res.json({ code: 200, data: false, msg: '缺少令牌' })
    }

    verifyToken(token)
    return res.json({ code: 200, data: true, msg: '令牌有效' })
  } catch {
    return res.json({ code: 200, data: false, msg: '令牌无效或已过期' })
  }
})

export default router
